#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2021/7/29 17:50
# @Author  : Samge
from itkz.resources.utils.log import Log


class BaseLogDb(object):

    # 爬虫对象
    spider = None
    # log信息队列，用于gui中读取显示
    log_queue = None

    def __tuple_to_str(self, value):
        if value is None:
            return None
        if type(value) is tuple:
            return ''.join(list(value))
        return value

    def name(self):
        return self.__class__.__name__

    def set_log_queue(self, log_queue):
        self.log_queue = log_queue

    def process_item(self, item, spider):
        self.spider = spider
        pass

    def log_info(self, *v):
        v = ' '.join(['%s' % str(s) for s in v])
        self.log_queue.put(v) if self.log_queue else None
        try:
            self.spider.log_info(v) if self.spider else None
        except Exception as e:
            Log().getlog().info(v)

    def log_error(self, *v):
        v = ' '.join(['%s' % str(s) for s in v])
        self.log_queue.put(v) if self.log_queue else None
        try:
            self.spider.log_error(v) if self.spider else None
        except Exception as e:
            Log().getlog().error(v)

    def close_connect(self):
        # 关闭游标和连接
        try:
            self.cursor.close()
            self.conn.close()
            self.child_close()
            self.log_info('释放数据库连接')
        except Exception as e:
            self.log_error(e)
            pass

    def child_close(self):
        """
        提供给子类处理的关闭操作
        """
        pass

    def need_update(self, spider):
        try:
            self.log_info(f"是否需要进行更新 spider.NEED_UPDATE={spider.NEED_UPDATE}")
            return spider.NEED_UPDATE
        except:
            return False

    def is_test(self, spider):
        try:
            self.log_info(f"是否测试模式 spider.IS_TEST={spider.IS_TEST}")
            return spider.IS_TEST
        except:
            return False

    def parse_encoding(self, row):
        """
        处理window中查询出来的中文乱码问题
        :param row:
        :return:
        """
        row = list(row)
        try:
            for i in range(len(row)):
                item = row[i]
                if type(item) is str:
                    row[i] = item.encode('latin1').decode('gbk')
        except Exception as e:
            # self.log_info(e)
            pass
        return row
